<template>
  <el-card class="box-card" v-loading="loading">
    <div slot="header" class="clearfix">
      <span>信息提取</span>
    </div>
    <el-form label-width="120px" :model="formLabelAlign" :rules="rules"  ref="formLabelAlign">
      <el-form-item label="选择算法" prop="algorithm">
        <el-radio-group v-model="formLabelAlign.algorithm">
          <el-popover
            placement="top"
            width="200"
            trigger="hover"
            content="请输入嵌入秘密信息后的载密图像，否则会失败。"
          >
            <el-button slot="reference">
              <el-radio label="1">明文图像可逆信息恢复</el-radio>
            </el-button>
          </el-popover>
          <el-popover
            placement="top"
            width="200"
            trigger="hover"
            content="请输入嵌入秘密信息后的加密载密图像，否则会失败。"
          >
            <el-button slot="reference">
              <el-radio label="2">加密图像可逆信息恢复</el-radio>
            </el-button>
          </el-popover>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="选择载密图片" prop="containSecretImage" ref="containSecretImage">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8888/user/upload"
          :on-success="handleAvatarSuccess"
          :show-file-list="false"
        >
          <div class="originimg" v-if="formLabelAlign.containSecretImage" @click.stop>
            <img :src="formLabelAlign.containSecretImage" alt="" class="avatar" />
            <div class="img-bg">
              <span @click.stop="remove">
                <i class="el-icon-delete"></i>
              </span>
            </div>
          </div>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item
        :class="
          formLabelAlign.algorithm === '2'
            ? 'submitButton2 submitButton'
            : 'submitButton'
        "
      >
        <el-button
          type="primary"
          v-if="formLabelAlign.algorithm === '2'"
          @click="submitForm('originImg')"
        >提取原图像</el-button
        >
        <el-button
          type="primary"
          v-if="formLabelAlign.algorithm === '2'"
          @click="submitForm('sercetInfo')"
        >提取秘密信息</el-button
        >
        <el-button type="primary" @click="submitForm('allInfo')"
        >提取并恢复</el-button
        >
      </el-form-item>
    </el-form>
    <el-dialog
      :visible.sync="infoVisible"
      width="500px"
      :title="
        dialogTitle === 'originImg'
          ? '恢复后的图像'
          : dialogTitle === 'sercetInfo'
          ? '秘密信息'
          : '全部信息'
      "
      center
    >
      <el-card class="el-cards">
        <div class="form-item" v-if="dialogTitle !== 'sercetInfo'">
          <span class="form-item-label" v-if="dialogTitle === 'allInfo'"
          >恢复后的图像:</span
          >
          <div class="originimg">
            <img width="300px" :src="restoredImage || formLabelAlign.containSecretImage" alt="" />
            <div class="img-bg">
              <span @click="handleDownload()">
                <i class="el-icon-download"></i>
              </span>
            </div>
          </div>
        </div>
        <div class="form-item" v-if="dialogTitle !== 'originImg'">
          <span class="form-item-label" v-if="dialogTitle === 'allInfo'"
          >提取的秘密信息:</span
          >
          <span class="secretData">{{
              extractedSecretData || "这是一条提取的秘密信息"
            }}</span>
        </div>
      </el-card>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  name: "Extract",
  data() {
    return {
      loading:false,
      isEmbed:1, //提取
      restoredImage:"",// 恢复后的图像
      extractedSecretData:'',//提取的秘密信息
      imageKey: "", //图像密钥
      dataKey: "", //信息密钥
      dialogTitle: "",
      infoVisible: false,
      formLabelAlign: {
        algorithm: "1",//算法选择 1，2
        containSecretImage:"",// 载密图像
      },
      rules: {
        containSecretImage: [
          { required: true, message: "请上传图片", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    // 移除文件
    remove(file) {
      this.formLabelAlign.containSecretImage = "";
    },
    // 下载
    handleDownload() {
      const name = "恢复后的图片";
      const url = this.restoredImage;
      var image = new Image();
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png");
        var a = document.createElement("a");
        a.download = name;
        a.href = url;
        a.click();
      };
      image.src = url;
    },
    // 提交
    submitForm(dialogTitle) {
      this.$refs.formLabelAlign.validate((valid) => {
        const { containSecretImage } = this.formLabelAlign;
        if(valid){
          this.dialogTitle = dialogTitle;
          this.loading = true
          // 明文提取
          if (this.formLabelAlign.algorithm === "1") {
            // 调用算法
            this.$axios.post("http://127.0.0.1:7777/extract", {
              containSecretImage,
              extractType:0,
              isEncry: this.formLabelAlign.algorithm === '2' // 是否加密 1 不加密 2 加密
            }).then(res=>{
              console.log(res)
              if (res.data) {
                const imageData = res.data.image;
                const binaryData = atob(imageData);
                const byteArray = new Uint8Array(binaryData.length);
                for (let i = 0; i < binaryData.length; i++) {
                  byteArray[i] = binaryData.charCodeAt(i);
                }
                const blob = new Blob([byteArray], {type: `${+new Date()}明文恢复图片.png`});
                this.restoredImage = URL.createObjectURL(blob);
                this.extractedSecretData = res.data.message;
                // this.restoredImage = res.restoredImage
                // this.extractedSecretData = res.extractedSecretData
                // this.openModal()
                var formData = new FormData();
                formData.append('file', blob, `${+new Date()}明文恢复图片.png`);
                fetch('http://localhost:8888/user/upload',{
                  method: 'POST',
                  body: formData
                }).then(response => response.json())
                  .then(res => {
                    this.loading = false
                    console.log(res, 'res2322222222222')
                    // 处理响应
                    this.restoredImage =  res.url
                    this.openModal()

                    const param = {
                      isEmbed:this.isEmbed,
                      containSecretImage,
                      restoredImage:this.restoredImage,
                      extractedSecretData:this.extractedSecretData
                    }

                    // 后端接口存储记录
                    this.$axios.post("http://localhost:8888/user/log", {
                      ...param
                    }).then(res=>{
                      this.loading = false
                    })
                  })
                  .catch(error => {
                    this.loading = false
                    // 处理错误
                    console.error('Error uploading file:', error);
                  });
              }
                else{
                this.loading = false
                  this.$message.error('提取失败')
              }
            }).catch(err=>{
              this.loading = false
              this.$message.error('很抱歉！提取和恢复失败，请上传正确的载密图像！')
            })
          //  密文提取
          }else{
            switch (dialogTitle) {
              // 提取原图像
              case 'originImg':
                // 算法
                this.$axios.post("http://127.0.0.1:7777/extract", {
                  containSecretImage,
                  isEncry: this.formLabelAlign.algorithm === '2', // 是否加密 1 不加密 2 加密
                  extractType: 1 // 提取类型 1 原图像 2 秘密信息  3 全部提取
                },{responseType: 'blob'}).then(res=>{
                  console.log(res,'eqwewqewqe')
                  if (res.data) {
                    let blob = new Blob([res.data], { type: res.headers['content-type']});
                    // this.restoredImage = URL.createObjectURL(blob);

                    var formData = new FormData();
                    formData.append('file', blob, `${+new Date()}加密载密图像提取.png`);
                    fetch('http://localhost:8888/user/upload',{
                      method: 'POST',
                      body: formData
                    }).then(response => response.json())
                      .then(res => {
                        this.loading = false
                        console.log(res)
                        this.restoredImage =  res.url

                        this.openModal()
                        const param = {
                          isEmbed:this.isEmbed,
                          carrierEncryptedImage:containSecretImage,
                          imageKey:this.imageKey,
                          ciphertextType:1,
                          restoredImage:this.restoredImage
                        }
                        // 后端接口存储记录
                        this.$axios.post("http://localhost:8888/user/log", {
                          ...param
                        }).then(res=>{

                        })
                      })

                  }
                }).catch(err=>{
                  this.loading = false
                  this.$message.error('很抱歉！图像恢复失败，请上传正确的载密加密图像！')
                })
                break;
              // 提取秘密信息
              case 'sercetInfo':
                this.$axios.post("http://127.0.0.1:7777/extract", {
                  containSecretImage,
                  isEncry: this.formLabelAlign.algorithm === '2', // 是否加密 1 不加密 2 加密
                  extractType: 2 // 提取类型 1 原图像 2 秘密信息  3 全部提取
                }).then(res=>{
                  if (res) {
                    this.extractedSecretData = res.data
                    this.openModal()
                    const param = {
                      isEmbed:this.isEmbed,
                      carrierEncryptedImage:containSecretImage,
                      dataKey:this.dataKey,
                      ciphertextType:2,
                      extractedSecretData:this.extractedSecretData
                    }
                    // 后端接口存储记录
                    this.$axios.post("http://localhost:8888/user/log", {
                      ...param
                    }).then(res=>{
                      this.loading = false
                    })
                  }
                }).catch(err=>{
                  this.loading = false
                  this.$message.error('很抱歉！秘密信息提取失败，请上传正确的载密加密图像！')
                })
                break;
              // 提取并恢复
              default:
                // 算法
                this.$axios.post("http://127.0.0.1:7777/extract", {
                  containSecretImage,
                  isEncry: this.formLabelAlign.algorithm === '2', // 是否加密 1 不加密 2 加密
                  extractType: 3 // 提取类型 1 原图像 2 秘密信息  3 全部提取
                }).then(res=>{
                  if (res.data) {
                    const imageData = res.data.image;
                    const binaryData = atob(imageData);
                    const byteArray = new Uint8Array(binaryData.length);
                    for (let i = 0; i < binaryData.length; i++) {
                      byteArray[i] = binaryData.charCodeAt(i);
                    }
                    const blob = new Blob([byteArray], {type: 'image/png'});
                    this.extractedSecretData = res.data.message;
                    var formData = new FormData();
                    formData.append('file', blob, `${+new Date()}加密载密图像提取.png`);
                    fetch('http://localhost:8888/user/upload',{
                      method: 'POST',
                      body: formData
                    }).then(response => response.json())
                      .then(res => {
                        this.loading = false
                        this.restoredImage =  res.url
                        this.openModal()
                        const param = {
                          isEmbed:this.isEmbed,
                          imageKey:this.imageKey,
                          carrierEncryptedImage:containSecretImage,
                          dataKey:this.dataKey,
                          restoredImage:this.restoredImage,
                          ciphertextType:2,
                          extractedSecretData:this.extractedSecretData
                        }
                        // 后端接口存储记录
                        this.$axios.post("http://localhost:8888/user/log", {
                          ...param
                        }).then(res=>{

                        })
                      })
                  }
                }).catch(err=>{
                  this.loading = false
                  this.$message.error('很抱歉！提取和恢复失败，请上传正确的载密加密图像！')
                })
                break;
            }
          }
        }
      })
    },
    // 上传成功，打开弹窗
    openModal(){
      this.$message({
        message: "提取成功",
        type: "success",
      });
      setTimeout(() => {
        this.infoVisible = true;
      }, 1000);
    },
    // 上传文件
    handleAvatarSuccess(res, file, fileList) {
      if (res.url) {
        this.$message({
          message: "上传成功",
          type: "success",
        });
        this.formLabelAlign.containSecretImage = res.url;
        this.$refs.containSecretImage.clearValidate();
      }
    },
  },
};
</script>

<style scoped>
.el-button {
  border: none;
}
.box-card {
  width: 700px;
  height: 500px;
  background: #fff;
  padding: 20px;
  border: 1px solid #ebebeb;
  border-radius: 3px;
  position: relative;
  box-shadow: 0 0 8px rgba(232, 237, 250, 0.6),
  0 2px 4px 0 rgba(232, 237, 250, 0.5);
}
.submitButton {
  margin-top: 190px;
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translate(-50%, -50%);
  margin-bottom: 0;
}
.submitButton2 {
  left: 45%;
}

.clearfix {
  text-align: center;
  font-size: 24px;
  font-weight: 500;
}

/deep/.submitButton > .el-form-item__content {
  margin-left: 0px !important;
  text-align: center;
}

.form-item {
  display: flex;
  margin-top: 20px;
}
.form-item-label {
  margin-right: 20px;
  min-width: 105px;
}
/deep/.el-cards .el-card__body {
  display: flex;
  align-items: center;
  flex-direction: column;
}
.secretData {
  width: 300px;
}
.originimg {
  position: relative;
  width: 100%;
  height: 100%;
}
.img-bg {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-icon-delete,
.el-icon-download {
  display: none;
}
.img-bg:hover {
  background: rgba(0, 0, 0, 0.5);
  cursor: pointer;
}
.img-bg:hover .el-icon-delete,
.img-bg:hover .el-icon-download {
  display: block;
  font-size: 36px;
  color: #fff;
}

/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
